<template>
  <div>
    <div v-for="(item, index) in list" :key="index" class="card-item">
      <!-- 商品预览图:选项卡，步进条，删除按钮 -->
      <van-swipe-cell v-if="item.id != null">
        <van-checkbox
          class="card-item__item"
          :name="item.id"
          v-model="item.selected"
          @click="
            () => {
              item.selected = !item.selected
              onItemChange(item)
            }
          "
        >
          <van-card
            class="card"
            :title="item.name"
            :num="item.count"
            :thumb="'data:image;base64,' + item.images[0]"
            :price="item.current_price"
            @click.stop
          >
            <div slot="desc">
              <div style="width:200px;" class="van-ellipsis">
                {{ item.info }}
              </div>
            </div>
            <div slot="bottom">
              <van-row gutter="100" type="flex">
                <van-col>
                  <van-stepper
                    :value="item.count"
                    @change="
                      value => {
                        item.count = value
                        onItemChange(item)
                      }
                    "
                  />
                </van-col>
                <van-col style="margin:5px;padding:0px;">
                  <a style="color:#A6ACAF;" @click="onItemClick(item)"
                    >查看详情</a
                  >
                </van-col>
              </van-row>
            </div>
          </van-card>
        </van-checkbox>
        <template slot="right">
          <van-button
            style="height:100%;"
            square
            type="danger"
            text="删除"
            @click="onCancelClick(item)"
          />
        </template>
      </van-swipe-cell>
    </div>
    <div style="height:50px;" />
    <van-submit-bar
      :price="totalPrice"
      :disabled="disableSubmit"
      :button-text="submitBarText"
      @submit="onSubmit"
    />
  </div>
</template>

<script>
import { axios, API_URL } from "../../api"
import {
  Checkbox,
  CheckboxGroup,
  Card,
  SubmitBar,
  Toast,
  Button,
  Stepper,
  SwipeCell,
  Row,
  Col
} from "vant"

export default {
  components: {
    [Card.name]: Card,
    [Checkbox.name]: Checkbox,
    [SubmitBar.name]: SubmitBar,
    [CheckboxGroup.name]: CheckboxGroup,
    [Button.name]: Button,
    [Row.name]: Row,
    [Col.name]: Col,
    [Stepper.name]: Stepper,
    [SwipeCell.name]: SwipeCell
  },

  data() {
    return {
      value: 1,
      list: [],
      selected: true,
      submitBarText: "",
      totalPrice: 0,
      disableSubmit: true
    }
  },

  /* 监测输入数据改变 */
  watch: {
    list: {
      handler: function() {
        let count = this.list.reduce(
          (total, item) => total + (item.selected ? item.count : 0),
          0
        )
        this.submitBarText = "结算" + (count ? `(${count})` : "")

        this.totalPrice =
          this.list.reduce(
            (total, item) =>
              total + (item.selected ? item.current_price * item.count : 0),
            0
          ) * 100

        this.disableSubmit = !this.list.some(item => item.selected)
      },
      deep: true
    }
  },

  methods: {
    onSubmit() {
      this.$router.push({ name: "submit" })
    },
    onItemChange(item) {
      axios
        .put(
          API_URL + "cart",
          {
            item_id: item.item_id,
            selected: item.selected,
            count: item.count
          },
          {
            headers: {
              Authorization: this.$store.state.customer_token
            }
          }
        )
        .then(() => {})
        .catch(err => {
          console.error(err)
        })
    },
    onCancelClick(item) {
      axios
        .delete(API_URL + "cart", {
          params: {
            item_id: item.item_id
          },
          headers: {
            Authorization: this.$store.state.customer_token
          }
        })
        .then(() => {
          Toast("删除商品成功")
          this.getCartList()
        })
        .catch(err => {
          console.error(err)
        })
    },
    onItemClick(item) {
      this.$router.push({ name: "item", params: { item_id: item.item_id } })
    },
    getCartList() {
      // 刷新购物车页面
      this.list = []
      // 获取商品的item_id
      axios
        .get(API_URL + "cart", {
          headers: {
            Authorization: this.$store.state.customer_token
          }
        })
        .then(response => {
          let items = response.data.items
          items.forEach(item => {
            var tmpItem = { selected: false, count: 0 }
            // 通过item_id获取商品信息
            this.list.push(tmpItem)
            axios
              .get(API_URL + "items/" + item.item_id, {})
              .then(response => {
                tmpItem.item_id = item.item_id
                tmpItem.id = +item.item_id
                tmpItem.selected = item.selected
                tmpItem.count = item.count
                tmpItem.name = response.data.name
                tmpItem.current_price = response.data.current_price
                tmpItem.original_price = response.data.original_price
                tmpItem.in_stock = response.data.in_stock
                tmpItem.info = response.data.info
                tmpItem.sales = response.data.sales
                tmpItem.shop_id = response.data.shop_id
                tmpItem.images = response.data.images
                this.list = this.list.splice(0)
              })
              .catch(err => {
                console.error(err)
              })
          })
        })
        .catch(err => {
          console.error(err)
        })
    }
  },
  mounted: function() {
    this.getCartList()
  }
}
</script>

<style scoped>
.card-item {
  padding: 0;
}
.card-item__item {
  position: relative;
  padding: 0 0 0 15px;
}

.van-card__price {
  color: #f44;
  padding: 5px 0;
}

.card {
  width: 100%;
  background-color: #ffffff;
}
</style>
